package com.cpip.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpip.common.pojo.*;
import com.cpip.order.mapper.*;
import com.cpip.order.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class OrdersSreviceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private BuyerMapper buyerMapper;
    @Autowired
    private ManufacturerMapper manufacturerMapper;
    @Autowired
    private ApplyInformationMapper applyInformationMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Page<Orders> selectAll(int current, int pageSize, String query) {
        Page<Orders> page = new Page<>(current, pageSize);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(query)) {
            page.setRecords(ordersMapper.mySelectList(page, wrapper));
            return page;
        } else {
            wrapper.like("goods_name", query)
                    .or().like("status", query)
                    .or().like("manufacturer_name", query)
                    .or().like("manufacturer_address", query)
                    .or().like("buyer_name", query);
            page.setRecords(ordersMapper.mySelectList(page, wrapper));
            return page;
        }
    }

    @Override
    public Page<Orders> selectOrdersByBuyerId(int buyerId, int current, int pageSize, String query) {
        Page<Orders> page = new Page<>(current, pageSize);
        if (StringUtils.isEmpty(query)) {
            QueryWrapper<Orders> wrapper = new QueryWrapper<>();
            wrapper.eq("buyer_id", buyerId);
            return ordersMapper.selectPage(page, wrapper);
        } else {
            QueryWrapper<Orders> wrapper = new QueryWrapper<>();
            wrapper.eq("buyer_id", buyerId)
                    .like("goods_name", query)
                    .or().like("status", query)
                    .or().like("manufacturer_name", query)
                    .or().like("manufacturer_address", query)
                    .or().like("buyer_name", query);
            return ordersMapper.selectPage(page, wrapper);
        }
    }

    @Override
    public Page<Orders> selectOrdersByManufacturerId(int manufacturerId, int current, int pageSize, String query) {
        Page<Orders> page = new Page<>(current, pageSize);
        if (StringUtils.isEmpty(query)) {
            QueryWrapper<Orders> wrapper = new QueryWrapper<>();
            wrapper.eq("manufacturer_id", manufacturerId);
            return ordersMapper.selectPage(page, wrapper);
        } else {
            QueryWrapper<Orders> wrapper = new QueryWrapper<>();
            wrapper.eq("manufacturer_id", manufacturerId)
                    .like("goods_name", query)
                    .or().like("status", query)
                    .or().like("buyer_name", query);
            return ordersMapper.selectPage(page, wrapper);
        }
    }

    @Override
    public void returnGoods(Long orderId, String status) {
        Orders orders = ordersMapper.selectById(orderId);
        orders.setStatus(status);
        ordersMapper.updateById(orders);
        //更新采购订单状态
        QueryWrapper<ApplyInformation> applyInformationQueryWrapper = new QueryWrapper<>();
        applyInformationQueryWrapper.eq("buyer_id", orders.getBuyerId())
                .eq("goods_name", orders.getGoodsName());
        List<ApplyInformation> applyInformations = applyInformationMapper.selectList(applyInformationQueryWrapper);
        if (status.equals("申请退货") && applyInformations != null) {
            for (ApplyInformation applyInformation : applyInformations) {
                applyInformation.setStatus("退货中");
                applyInformationMapper.updateById(applyInformation);
            }
        }
        if (status.equals("已签收") && applyInformations != null) {
            for (ApplyInformation applyInformation : applyInformations) {
                applyInformation.setStatus("已完成");
                applyInformationMapper.updateById(applyInformation);
            }
        }
    }

    @Override
    public int receiveReturnGoods(Long orderId) {
        Orders orders = ordersMapper.selectById(orderId);
        //增加货物库存
        Goods goods = goodsMapper.selectById(orders.getGoodsId());
        UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
        goodsUpdateWrapper.eq("goods_id", orders.getGoodsId())
                .set("goods_num", goods.getGoodsNum() + orders.getGoodsNum());
        goodsMapper.update(null, goodsUpdateWrapper);
        //金额交易
        Manufacturer manufacturer = manufacturerMapper.selectById(orders.getManufacturerId());
        Buyer buyer = buyerMapper.selectById(orders.getBuyerId());
        UpdateWrapper<Buyer> buyerUpdateWrapper = new UpdateWrapper<>();
        int result1 = buyer.getMoney() + orders.getTotalPrice();
        buyerUpdateWrapper.eq("buyer_id", orders.getBuyerId())
                .set("money", result1);
        buyerMapper.update(null, buyerUpdateWrapper);
        int result2 = manufacturer.getMoney() - orders.getTotalPrice();
        UpdateWrapper<Manufacturer> manuUpdateWrapper = new UpdateWrapper<>();
        manuUpdateWrapper.eq("manufacturer_id", orders.getManufacturerId())
                .set("money", result2);
        manufacturerMapper.update(null, manuUpdateWrapper);
        //更新采购订单状态
        QueryWrapper<ApplyInformation> applyInformationQueryWrapper = new QueryWrapper<>();
        applyInformationQueryWrapper.eq("buyer_id", orders.getBuyerId())
                .eq("goods_name", orders.getGoodsName());
        List<ApplyInformation> applyInformations = applyInformationMapper.selectList(applyInformationQueryWrapper);
        for (ApplyInformation applyInformation : applyInformations) {
            applyInformation.setStatus("已接单");
            applyInformationMapper.updateById(applyInformation);
        }
        //删除订单
        return ordersMapper.deleteById(orderId);
    }

    @Override
    public String add(Long cartId) {
        //订单信息生成
        Orders orders = new Orders();
        Cart cart = cartMapper.selectById(cartId);
        orders.setCartId(cartId);
        orders.setGoodsId(cart.getGoodsId());
        orders.setGoodsName(cart.getGoodsName());
        orders.setGoodsPrice(cart.getGoodsPrice());
        orders.setGoodsNum(cart.getGoodsNum());
        orders.setTotalPrice(cart.getTotalPrice());
        orders.setManufacturerId(cart.getManufacturerId());
        orders.setManufacturerName(cart.getManufacturerName());
        orders.setManufacturerAddress(cart.getManufacturerAddress());
        orders.setManufacturerContact(cart.getManufacturerContact());
        orders.setBuyerId(cart.getBuyerId());
        orders.setBuyerName(cart.getBuyerName());
        orders.setBuyerAddress(cart.getBuyerAddress());
        orders.setBuyerContact(cart.getBuyerContact());
        orders.setStatus("待发货");
        Manufacturer manufacturer = manufacturerMapper.selectById(orders.getManufacturerId());
        Buyer buyer = buyerMapper.selectById(orders.getBuyerId());
        //判断库存是否满足采购
        Goods goods = goodsMapper.selectById(orders.getGoodsId());
        if (goods.getGoodsNum() < orders.getGoodsNum()) {
            return "库存不足，请联系厂家或购买其它货物！！！";
        }
        //判断库存是否满足采购
        if (buyer.getMoney() < orders.getTotalPrice()) {
            return "金额不足，请充值！！！";
        }
        //金额交易
        UpdateWrapper<Buyer> buyerUpdateWrapper = new UpdateWrapper<>();
        int result1 = buyer.getMoney() - orders.getTotalPrice();
        buyerUpdateWrapper.eq("buyer_id", orders.getBuyerId())
                .set("money", result1);
        buyerMapper.update(null, buyerUpdateWrapper);
        int result2 = manufacturer.getMoney() + orders.getTotalPrice();
        UpdateWrapper<Manufacturer> manuUpdateWrapper = new UpdateWrapper<>();
        manuUpdateWrapper.eq("manufacturer_id", orders.getManufacturerId())
                .set("money", result2);
        manufacturerMapper.update(null, manuUpdateWrapper);
        //删除厂家库存
        UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
        goodsUpdateWrapper.eq("goods_id", orders.getGoodsId())
                .set("goods_num", goods.getGoodsNum() - orders.getGoodsNum());
        goodsMapper.update(null, goodsUpdateWrapper);
        //逻辑删除购物车,设置购物车状态为已付款
        UpdateWrapper<Cart> cartUpdateWrapper = new UpdateWrapper<>();
        cartUpdateWrapper.eq("cart_id", cartId)
                .set("status", "已付款");
        cartMapper.update(null, cartUpdateWrapper);
        cartMapper.deleteById(cartId);
        //设置采购订单状态
        QueryWrapper<ApplyInformation> applyInformationQueryWrapper = new QueryWrapper<>();
        applyInformationQueryWrapper.eq("buyer_id", orders.getBuyerId())
                .eq("goods_name", orders.getGoodsName());
        List<ApplyInformation> applyInformations = applyInformationMapper.selectList(applyInformationQueryWrapper);
        if (applyInformations != null) {
            for (ApplyInformation applyInformation : applyInformations) {
                applyInformation.setStatus("待发货");
                applyInformationMapper.updateById(applyInformation);
            }
        }
        //生成订单
        ordersMapper.insert(orders);
        return "结算成功";
    }

    @Override
    public void update(Long orderId, String status) {
        Orders orders = ordersMapper.selectById(orderId);
        //设置订单状态
        orders.setStatus(status);
        ordersMapper.updateById(orders);
        //更新采购订单状态
        QueryWrapper<ApplyInformation> applyInformationQueryWrapper = new QueryWrapper<>();
        applyInformationQueryWrapper.eq("buyer_id", orders.getBuyerId())
                .eq("goods_name", orders.getGoodsName());
        List<ApplyInformation> applyInformations = applyInformationMapper.selectList(applyInformationQueryWrapper);
        if (status.equals("已签收") && applyInformations != null) {
            for (ApplyInformation applyInformation : applyInformations) {
                applyInformation.setStatus("已完成");
                applyInformationMapper.updateById(applyInformation);
            }
        } else {
            for (ApplyInformation applyInformation : applyInformations) {
                applyInformation.setStatus("待签收");
                applyInformationMapper.updateById(applyInformation);
            }
        }
    }

    @Override
    public int delete(int buyerId) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("buyer_id", buyerId);
        return ordersMapper.delete(wrapper);
    }
}
